package main.com.pyjioh.core;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import main.com.pyjioh.R;
import main.com.pyjioh.accounts.AccountTypesProvider;
import main.com.pyjioh.accounts.AccountsTypesListAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;

public class ApodController {
	private ImageView mImageView;
	private ImageDownloader mImageDownloader = new ImageDownloader();
	private ApodModel mApodModel = ApodModel.getInstance();
	private Activity mAstropodActivity;

	private static ApodController instance;

	private ApodController() {
	}

	public static synchronized ApodController getInstance() {
		if (instance == null)
			instance = new ApodController();
		return instance;
	}

	private String formatDate(Date date) {
		return new SimpleDateFormat("dd MMM yyyy").format(date);
	}

	public void refreshActivity() {
		Button buttonDate = (Button) mAstropodActivity
				.findViewById(R.id.button_select_date);
		buttonDate.setText(formatDate(mApodModel.getCalendar().getTime()));

		mImageView = (ImageView) mAstropodActivity.findViewById(R.id.ImageView);
		mImageDownloader.download(mApodModel.getImageURL(), mImageView);
	}

	public void showSelectAccountTypeDialog(OnClickListener dialogListener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(mAstropodActivity);
		builder.setTitle(R.string.menu_share_caption);
		builder.setAdapter(new AccountsTypesListAdapter(mAstropodActivity,
				AccountTypesProvider.accountTypes), dialogListener);
		builder.create().show();
	}

	public void showNextDay() {
		mApodModel.incDay();
		refreshActivity();
	}

	public void showPrevDay() {
		mApodModel.decDay();
		refreshActivity();
	}

	public void showSelectDateDialog() {
		Calendar calendar = mApodModel.getCalendar();
		new DatePickerDialog(mAstropodActivity, new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				mApodModel.setDate(year, monthOfYear, dayOfMonth);
				refreshActivity();
			}
		}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH)).show();
	}

	public void setActivity(Activity astropodActivity) {
		mAstropodActivity = astropodActivity;
	}

}
